/******************************************************************
 * Created by: GOH CHEE HONG                                      
 * Date of Creation: 22/AUG/2008     
 * Date of last modification: 
 *                                                                
 * Description: SECURITY TOOLS
 ******************************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Pbdms.Common.CryptoUtils;
using Org.BouncyCastle.Bcpg.OpenPgp;
using Org.BouncyCastle.Utilities.Encoders;
using System.IO;

namespace Pbdms.Forms.Tools
{
    public partial class FrmSecurityTools : Form
    {
        public FrmSecurityTools()
        {
            InitializeComponent();
            Pbdms.Common.Global.paintBackGround(this);
        }
        /// <summary>
        /// encrypt event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnEncrypt_Click(object sender, EventArgs e)
        {
            try
            {

                    PgpPublicKey pubKey = null;

                    pubKey = Program.keyControl.readSecretKey().PublicKey;

                    openFileDia.Filter = "All files (*.*)|*.*" ;
                    openFileDia.FilterIndex = 2 ;

                    //
                    try
                    {
                        Encrypter encProcessor = new Encrypter();

                        string fileIn = null;
                        string encFile = null; ;
                        openFileDia.Title = "Please select a file to encrypt";
                        
                        DialogResult result = openFileDia.ShowDialog();
                        if (result == DialogResult.Cancel)
                        {
                            Common.Global.showMsgOneButton("You've cancelled the operation", 'I');
                        }
                        else if (result == DialogResult.OK)
                        {
                            fileIn = openFileDia.FileName;
                            saveFileDia.Title = "Please select a location to save the encrypted file";
                            DialogResult saveResult = saveFileDia.ShowDialog();
                            if (saveResult == DialogResult.Cancel)
                            {
                                Common.Global.showMsgOneButton("You've cancelled the operation", 'I');
                            }
                            else if (saveResult == DialogResult.OK)
                            {

                                encFile = saveFileDia.FileName;
                                Boolean success= encProcessor.EncryptFile(encFile, fileIn, pubKey, true);
                            }
                        }


                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
 
            }
            catch (Exception ex)
            {
                Common.Global.showMsgOneButton("Please select an valid public key to encrypt the file", 'E');
            }
        }
        //Decrypter event handler
        private void btnDecrypt_Click(object sender, EventArgs e)
        {
            try
            {
                openFileDia.Title = "Please select a encrypted file to decrypt";
                openFileDia.Filter = "All files (*.*)|*.*";
                openFileDia.FilterIndex = 2;
                string fileToDecrypt = null;
                string fileOut = null;
                DialogResult result = openFileDia.ShowDialog();
                if (result == DialogResult.Cancel)
                {

                }
                else if (result == DialogResult.OK)
                {
                    fileToDecrypt = openFileDia.FileName;
                    saveFileDia.Title = "Please choose a location to save the decrypted file";
                    DialogResult saveResult = saveFileDia.ShowDialog();
                    if (saveResult == DialogResult.OK)
                    {
                        try
                        {
                            PgpPrivateKey priKey = Program.keyControl.readPrivateKey();
                            fileOut = saveFileDia.FileName;
                            Decrypter decrypter = new Decrypter();
                            //PgpSecretKeyManager secManager = new PgpSecretKeyManager();
                            decrypter.DecryptFile(fileOut,fileToDecrypt, priKey );
                            MessageBox.Show("Success in decrypting the file");
                        }
                        catch (Exception ex)
                        {
                            Common.Global.showMsgOneButton(ex.Message, 'E');
                        }
                    }
                }


            }
            catch (Exception ex)
            {
                Common.Global.showMsgOneButton("Please select an valid public key to encrypt the file", 'E');
            }
        }
        /// <summary>
        /// sign a file
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDigitalSign_Click(object sender, EventArgs e)
        {
            try
            {
                //string secKey = grdvSecretKeys.Rows[grdvSecretKeys.CurrentRow.Index].Cells[0].FormattedValue.ToString();
                Stream fileOutStream = null;
                try
                {
                    //PgpSecretKeyManager secManager = new PgpSecretKeyManager();
                    PgpSecretKey secKey = Program.keyControl.readSecretKey();
                    PgpPrivateKey priKey = Program.keyControl.readPrivateKey();
                    Signer signer = new Signer();
                    openFileDia.Title = "Please select a file to be digitally signed";
                    openFileDia.Filter = "All files (*.*)|*.*";
                    openFileDia.FilterIndex = 2;
                    string fileIn = null;
                    DialogResult result = openFileDia.ShowDialog();
                    if (result == DialogResult.OK)
                    {
                        fileIn = openFileDia.FileName;
                        saveFileDia.Title = "Please select a location to save your file";
                        DialogResult saveResult = saveFileDia.ShowDialog();
                        if (saveResult == DialogResult.OK)
                        {


                            fileOutStream = File.Create(saveFileDia.FileName);

                            signer.SignFile(fileIn, secKey, priKey, fileOutStream, true); //secManager.getasecretkey(secKey), fileOutStream,true);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Common.Global.showMsgOneButton(ex.Message, 'E');
                }
                finally
                {
                    fileOutStream.Close();
                }
            }
            catch (Exception ex)
            {
                Common.Global.showMsgOneButton("Please select a secret key to sign a document", 'E');
            }
        }
        /// <summary>
        /// verify a file
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnVerify_Click(object sender, EventArgs e)
        {
            openFileDia.Title = "Please select a digital signed file to be verified";
            openFileDia.Filter = "All files (*.*)|*.*";
            openFileDia.FilterIndex = 2;
            DialogResult result = openFileDia.ShowDialog();
            string fileIn = null;
            string fileOut = null;
            if (result == DialogResult.OK)
            {
                Verifier verifier = new Verifier();
                fileIn = openFileDia.FileName;
                saveFileDia.Title = "Please choose a location to save the decrypted signed file";
                DialogResult saveResult = saveFileDia.ShowDialog();
                if (saveResult == DialogResult.OK)
                {
                    fileOut = saveFileDia.FileName;

                    try
                    {
                        PgpPublicKey pubKey = Program.keyControl.readSecretKey().PublicKey;
                        string keyID = verifier.VerifyFile( fileOut,fileIn, pubKey);
                        MessageBox.Show("the file is from keyId " + keyID);
                    }
                    catch (Exception ex)
                    {
                        Common.Global.showMsgOneButton(ex.Message, 'E');
                    }
                }
            }
        }

        private void btnGen_Click(object sender, EventArgs e)
        {
            

            {
                Boolean alreadyExist = false;
                foreach (Form frm in (this.MdiParent.MdiChildren))
                {
                    frm.WindowState = FormWindowState.Normal;
                    
                    if (frm.GetType().Equals(typeof(Pbdms.Forms.Tools.FrmKeyPair)))
                    {
                        frm.WindowState = FormWindowState.Normal;
                        frm.Activate();
                        alreadyExist = true;
                        break;
                    }
                }
                if (!alreadyExist)
                {
                    Common.GUI.MsgBoxTwoButtons FrmQues = new Pbdms.Common.GUI.MsgBoxTwoButtons("Generating a new key pair will destroy the existing key pair.\n Do you still want to continue", 2, 'I');
                    FrmQues.ShowDialog();
            
                    int choice = FrmQues.returnValue;
                    if (choice == 1)
                    {
                        Pbdms.Forms.Tools.FrmKeyPair frmKey = new Pbdms.Forms.Tools.FrmKeyPair();
                        frmKey.setNotFirstTime();
                        frmKey.MdiParent = this.MdiParent;
                        frmKey.Show();
                    }
                }


            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            saveFileDia.Title = "Please select a location to save your public key";
            saveFileDia.Filter = "asc files (*.asc)|*.asc";
            saveFileDia.FilterIndex = 2;
            DialogResult saveResult = saveFileDia.ShowDialog();
            string filename = "";

            if (saveResult == DialogResult.OK)
            {
                filename = saveFileDia.FileName;
                PgpPublicKey pubKey = Program.keyControl.readSecretKey().PublicKey;
                Stream fileOut = File.Create(filename);
                pubKey.Encode(fileOut);
                fileOut.Close();
            }
        }
    }
}